package com.preparation.controller;

import com.preparation.domain.Topic;
import com.preparation.dto.R;
import com.preparation.service.ITopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/topics")
@CrossOrigin
public class TopicController {

    @Autowired
    private ITopicService topicService;

    // 增加话题
    @PostMapping
    public R addTopic(@RequestBody Topic topic) {
        boolean result = topicService.save(topic);
        return result ? R.success("添加成功") : R.error();
    }

    // 删除话题
    @DeleteMapping("/{id}")
    public R deleteTopic(@PathVariable Integer id) {
        boolean result = topicService.removeById(id);
        return result ? R.success("删除成功") : R.error();
    }

    // 修改话题
    @PutMapping("/{id}")
    public R updateTopic(@RequestBody Topic topic) {
        boolean result = topicService.updateById(topic);
        return result ? R.success("修改成功") : R.error();
    }

    // 根据ID查询话题
    @GetMapping("/{id}")
    public R getTopicById(@PathVariable Integer id) {
        Topic topic = topicService.getById(id);
        return topic != null ? R.success(topic, "查询成功") : R.error(404, "查询失败");
    }

    // 查询所有话题
    @GetMapping
    public R getAllTopics() {
        List<Topic> topicList = topicService.list();
        return R.success(topicList, "查询成功");
    }
}
